'use strict';
module.exports = {
  /**
   * 此函数名称
   * @url user/pub/test1 前端调用的url参数地址
   * @description 此函数描述
   * @param {Object} data 请求参数
   * @param {String} uniIdToken 用户token
   * @param {String} userInfo 当前登录用户信息（可信任，仅kh目录下的函数有此值）
   * pub目录下请求参数需要带上 need_user_info = true
   * @param {Object} util 公共工具包
   * @param {Object} filterResponse 过滤器返回的数据
   * @param {Object} originalParam 原始请求参数（包含了原始event和context）
   * data 请求参数 说明
   * @param {String} uid 当前登录用户id（可信任，仅kh目录下的函数有此值）
   * res 返回参数说明
   * @param {Number} code 错误码，0表示成功
   * @param {String} msg 详细信息
   */
  main: async (event) => {
    //  注意: userInfo 和 uid 是可信任的，但默认只有kh目录下的函数才有此值
    let {
      data = {}, userInfo, util, filterResponse, originalParam
    } = event;
    let {
      customUtil,
      uniID,
      config,
      pubFun,
      vk,
      db,
      _
    } = util;
    let {
      uid
    } = data;
    let res = {
      code: 0,
      msg: ""
    };
    
    let contractName = 'vk-contract'
    let userName = "uni-id-users"
    let msgName = "vk-message"
    let bonusRelateName = "vk-bonus-relate";
    // 业务逻辑开始----------------------------------------------------------- 
    // 可写与数据库的交互逻辑等等
    let whereJson = {
      status: 1,
      type: 1
    }
    const dbCmd = db.command
    let addTimeLong = new Date(vk.pubfn.timeFormat(new Date(),"yyyy-MM-dd")).getTime()
    whereJson["computed_time"] =  dbCmd.lte(addTimeLong)
    res.addTimeLong = addTimeLong

    let pageSize = 100
    let pageNum = 1
    let contractArr
    let obj = await vk.baseDao.select({
      dbName: contractName,
      pageKey: true,
      getCount: true,
      pageIndex: pageNum,
      pageSize: pageSize,
      whereJson: whereJson,
    }, util);
    if (obj.total > pageSize) {
      let count = obj.total / pageSize + 1
      let arr = []
      for (let i = 0; i < count; i++) {
        let info = await vk.baseDao.select({
          dbName: contractName,
          pageKey: true,
          getCount: true,
          pageIndex: i + 1,
          pageSize: pageSize,
          whereJson: whereJson,
        }, util);
        arr = arr.concat(info.rows)
      }
      contractArr = [].concat(arr)
    } else {
      contractArr = [].concat(obj.rows)
    }
    res.contractArr = contractArr
    
  
    let relateArr
    let obj1 = await vk.baseDao.select({
      dbName: bonusRelateName,
      pageKey: true,
      getCount: true,
      pageIndex: pageNum,
      pageSize: pageSize,
      whereJson: {
        status: 1,
        type: 1
      }
    }, util);
    if (obj1.total > pageSize) {
      let count = obj1.total / pageSize + 1
      let arr = []
      for (let i = 0; i < count; i++) {
        let info = await vk.baseDao.select({
          dbName: bonusRelateName,
          pageKey: true,
          getCount: true,
          pageIndex: i + 1,
          pageSize: pageSize,
          whereJson: {
            status: 1,
            type: 1
          }
        }, util);
        arr = arr.concat(info.rows)
      }
      relateArr = [].concat(arr)
    } else {
      relateArr = [].concat(obj1.rows)
    }
    res.relateArr = relateArr
    
    
    let bonusArr= []
    for (let j = 0; j < contractArr.length; j++) {
      let cItem = contractArr[j]
      bonusArr.push({
        _id: contractArr[j].sign_id,
        amount: contractArr[j].per_bonus * contractArr[j].stock,
      })
    }
    for (let k = 0; k < relateArr.length; k++) {
      let rItem = relateArr[k]
      bonusArr.push({
        _id: rItem.tuijian_id,
        amount: rItem.tuijian_per_bonus
      })
    }
    res.bonusArr = bonusArr
    let newObj = {}
    for (let h = 0; h < bonusArr.length; h++) {
      let hItem = bonusArr[h]
      if (newObj[hItem._id]) {
        newObj[hItem._id] += parseInt(hItem.amount)
      } else {
        newObj[hItem._id] = parseInt(hItem.amount)
      }
    }
    res.newObj= newObj
    for(let key in newObj) {
      let userRes = await db
        .collection(userName)
        .where({
          _id: key,
        })
        .get();
        // 购买人信息
      if (userRes.data.length > 0) {
        let userBuyInfo = userRes.data[0];
        if(!userBuyInfo.balance) {
          userBuyInfo.balance = 0
        }
        if (userBuyInfo.water_amount_back <= newObj[key]) {
          await vk.baseDao.update({
              dbName: userName,
              whereJson: {
                _id: userBuyInfo._id,
              },
              dataJson: {
                balance: parseInt(userBuyInfo.balance) + parseInt(userBuyInfo.water_amount_back),
                water_amount_back: 0
              },
            },
            event.util
          );
          await vk.baseDao.add({
            dbName: msgName,
            dataJson: {
              user_id: userBuyInfo._id,
              nickname: userBuyInfo.nickname,
              status: 1,
              amount: userBuyInfo.water_amount_back,
              msg: '返利积分发放',
              type: 1 // 返利积分发放  2 系统消息  3 提现审核消息  4订单审核信息  5 推荐积分发放
            }
          }, event.util);
          // 更新所有合同和所有关系
          for (let n = 0; n < contractArr.length; n++) {
            if (contractArr[n].sign_id == userBuyInfo._id) {
              await vk.baseDao.update({
                  dbName: contractName,
                  whereJson: {
                    _id: contractArr[n]._id,
                    type: 1
                  },
                  dataJson: {
                    status: 2
                  },
                },
                event.util
              );
            }
          }
          for (let f = 0; f < relateArr.length; f++) {
            if (relateArr[f].tuijian_id == userBuyInfo._id) {
              await vk.baseDao.update({
                  dbName: bonusRelateName,
                  whereJson: {
                    _id: relateArr[f]._id,
                    type: 1
                  },
                  dataJson: {
                    status: 2
                  },
                },
                event.util
              );
            }
          }
          
        } else {
          await vk.baseDao.update({
              dbName: userName,
              whereJson: {
                _id: userBuyInfo._id,
              },
              dataJson: {
                balance: parseInt(userBuyInfo.balance) + parseInt(newObj[key]),
                water_amount_back: parseInt(userBuyInfo.water_amount_back )- parseInt(newObj[key])
              },
            },
            event.util
          );
          await vk.baseDao.add({
            dbName: msgName,
            dataJson: {
              user_id: userBuyInfo._id,
              nickname: userBuyInfo.nickname,
              status: 1,
              amount: newObj[key],
              msg: '返利积分发放',
              type: 1 // 返利积分发放  2 系统消息  3 提现审核消息  4订单审核信息  5 推荐积分发放
            }
          }, event.util);
        }
      }
    }
    
    
    // 业务逻辑结束-----------------------------------------------------------
    return res;
  }
}